package cn.tedu.springbootmybatis.service.impl;

import cn.tedu.springbootmybatis.mapper.UserMapper;
import cn.tedu.springbootmybatis.pojo.dto.AdminAddNewDTO;
import cn.tedu.springbootmybatis.pojo.vo.AdminInfoVo;
import cn.tedu.springbootmybatis.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.List;


/**
 * 登录相关业务的实现类
 *
 * @author java@tedu.cn
 * @version 0.0.1
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;

    /**
     * 查询密码
     *
     * @param username
     * @return
     */
    @Override
    public String getPassword(String username) {
        return userMapper.getPassword(username);
    }

    /**
     * 获取全部用户列表
     *
     * @return
     */
    @Override
    public List<AdminInfoVo> getUserList() {
        return userMapper.getUserList();
    }

    /**
     * 注册用户
     *
     * @param adminAddNewDTO
     * @return
     */
    @Override
    public String register(AdminAddNewDTO adminAddNewDTO) {
        validateUsername(adminAddNewDTO.getUsername());
        int a = userMapper.add(adminAddNewDTO);
        if (a != 1) {
            throw new RuntimeException("操作失败");
        }
        return "操作成功";
    }

    private void validateUsername(String username) {
        if (username == null) {
            throw new RuntimeException("用户名不能为空");
        }
        int effectRow = userMapper.getUserByUsername(username);
        if(effectRow != 0){
            throw new RuntimeException("用户名已存在");
        }
    }

    /**
     * 修改用户
     *
     * @param adminAddNewDTO
     * @return
     */
    @Override
    public String updateUser(AdminAddNewDTO adminAddNewDTO) {
        validate(adminAddNewDTO);
        int a = userMapper.updateUser(adminAddNewDTO);
        if (a != 1) {
            throw new RuntimeException("操作失败");
        }
        return "操作成功";
    }

    /**
     * 校验所有属性是否都不为空
     *
     * @param adminAddNewDTO
     */
    private void validate(AdminAddNewDTO adminAddNewDTO) {
        if (adminAddNewDTO.getId() == null) {
            throw new RuntimeException("id不能为空");
        }
        boolean allFieldsNull = true; // 标记是否所有字段为空
        Field[] declaredFields = adminAddNewDTO.getClass().getDeclaredFields();
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            try {
                if (declaredField.get(adminAddNewDTO) != null) {
                    allFieldsNull = false;
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        if (allFieldsNull) {
            throw new RuntimeException("操作失败");
        }

    }

}
